package com.pri.chat.adapter;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.model.ZanModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GlideUtil;
import com.pri.chat.view.ImageViewPlus;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.vondear.rxtool.view.RxToast;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/7
 */
public class VideoListAdapter extends BaseQuickAdapter<DTBean, BaseViewHolder> {
    public static final String TAG = "VideoListAdapter";
    private static final String DATA_ONE = "dataOne";

    public VideoListAdapter(int layoutResId, @Nullable List<DTBean> data) {
        super(layoutResId, data);
        gsyVideoOptionBuilder = new GSYVideoOptionBuilder();

    }

    // 局部刷新item数据
    public void refreshPartItem(int position) {
        // 局部刷新的主要api，参数一：更新的item位置，参数二：item中被标记的某个数据
        notifyItemChanged(position, DATA_ONE);  // changePos 为0：数据1   为1：数据2
    }

    GSYVideoOptionBuilder gsyVideoOptionBuilder;

    private void resolveFullBtn(final StandardGSYVideoPlayer standardGSYVideoPlayer) {
        standardGSYVideoPlayer.startWindowFullscreen(mContext, true, true);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            for (Object payload : payloads) {
                switch (String.valueOf(payload)) {
                    case DATA_ONE:
                        holder.setText(R.id.tv_video_zan, mData.get(position).getZanNum() + "");
                        break;

                }
            }
        }
    }

    /**
     * 加载视频帧图
     *
     * @param imageView 展示图片view
     * @param url       视频链接
     * @param context   上下文
     */
    public static void loadCover(ImageView imageView, String url, Context context) {

        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        Glide.with(context)
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(1000000)
                                .centerCrop()
                )
                .load(url)
                .into(imageView);
    }

    @Override
    protected void convert(BaseViewHolder helper, DTBean item) {
        helper.addOnClickListener(R.id.iv_logo);
        helper.addOnClickListener(R.id.shareLinear);
        helper.addOnClickListener(R.id.zanLinear);
        helper.addOnClickListener(R.id.plLinear);

        helper.setText(R.id.tv_video_title, item.getContent());
        helper.setText(R.id.tv_video_name, item.getMemberName());
        helper.setText(R.id.tv_video_zan, item.getZanNum() + "");
        helper.setText(R.id.tv_video_pl, item.getPlNum()+"");
        ImageView zanImage = helper.getView(R.id.zanImage);
        if (item.getSfdz() == 0) {
            zanImage.setImageResource(R.mipmap.ic_zan_normal);
        } else {
            zanImage.setImageResource(R.mipmap.ic_zan_selected);
        }
        GlideUtil.getInstance().loadHeadImg(mContext, (ImageViewPlus) helper.getView(R.id.iv_logo), item.getHeadPic());
        StandardGSYVideoPlayer gsyVideoPlayer = helper.getView(R.id.detail_player);
        ImageView imageFengMian = helper.getView(R.id.imageFengMian);
        Glide.with(mContext).load(item.getVideoPath()+"?vframe/jpg/offset/0").into(imageFengMian);
        imageFengMian.setVisibility(View.VISIBLE);
        loadCover(imageFengMian, item.getVideoPath(), mContext);
        ImageView imageView = new ImageView(mContext);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
//        Glide.with(mContext).load(item.getImageUrl()).into(imageView);
        loadCover(imageView, item.getVideoPath(), mContext);
        String path = Environment.getExternalStorageDirectory()+"/com.pri.chat"+"/cache/video/";
        gsyVideoOptionBuilder
                .setIsTouchWiget(true)
                .setThumbImageView(imageView)
                .setUrl(item.getVideoPath())
                .setCacheWithPlay(true)
                .setCachePath(new File(path))
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setShowPauseCover(true)
                .setLooping(true)
                .setPlayTag(TAG)
                .setShowFullAnimation(true)
                .setNeedLockFull(true)
                .setPlayPosition(helper.getAdapterPosition())
                .setVideoAllCallBack(new GSYSampleCallBack() {

                    @Override
                    public void onPrepared(String url, Object... objects) {
                        super.onPrepared(url, objects);
                        imageFengMian.animate().alpha(0).setDuration(500).start();
                        if (!gsyVideoPlayer.isIfCurrentIsFullscreen()) {
                            //静音
//                          GSYVideoManager.instance().setNeedMute(true);
                        }

                    }

                    @Override
                    public void onEnterFullscreen(String url, Object... objects) {
                        super.onEnterFullscreen(url, objects);
                        GSYVideoManager.instance().setNeedMute(false);
                        gsyVideoPlayer.getCurrentPlayer().getTitleTextView().setText((String) objects[0]);
                    }

                    @Override
                    public void onQuitFullscreen(String url, Object... objects) {
                        super.onQuitFullscreen(url, objects);
                        //全屏不静音
//                                GSYVideoManager.instance().setNeedMute(true);
                    }
                }).build(gsyVideoPlayer);
        //增加title
        gsyVideoPlayer.getTitleTextView().setVisibility(View.GONE);
        //设置返回键
        gsyVideoPlayer.getBackButton().setVisibility(View.GONE);
        gsyVideoPlayer.getFullscreenButton().setVisibility(View.GONE);
        //设置全屏按键功能
        gsyVideoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resolveFullBtn(gsyVideoPlayer);
            }
        });
        if (helper.getAdapterPosition() == 0) {
            gsyVideoPlayer.startPlayLogic();
        }
//        helper.getView(R.id.tv_video_zan).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                httpLike(helper.getAdapterPosition(), helper);
//            }
//        });
    }

    private void httpLike(int pos, BaseViewHolder helper) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            if (mData.get(pos).getSfdz() == 0) {
                mData.get(pos).setSfdz(1);
                mData.get(pos).setZanNum(mData.get(pos).getZanNum() + 1);
            } else {
                mData.get(pos).setSfdz(0);
                mData.get(pos).setZanNum(mData.get(pos).getZanNum() - 1);

            }
            helper.setText(R.id.tv_video_zan, mData.get(pos).getZanNum() + "");
            RxToast.normal(baseBean.getMsg());
        };
        ZanModel zanModel = new ZanModel();
        zanModel.setBdzId(mData.get(pos).getId());
        zanModel.setDzrId(SharedHelper.readId(mContext));
        zanModel.setType(1);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(zanModel));
        HttpMethods.getInstance().saveDianZan(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }
}
